package com.starblink.store.memanage.ui

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.RemoveStoresEvent
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.store.databinding.ActivityMeManageBinding
import com.starblink.store.memanage.adapter.SubStoresHolder
import com.starblink.store.memanage.vm.MeManageVM
import com.starblink.store.recommend.part.RecommendStorePart

//@Route(path = RoutePage.Store.PAGE_MY_MANAGE)
class MeManageActivity : BaseTVMActivity<ActivityMeManageBinding, MeManageVM>() {

    @Autowired(name = RoutePage.Store.FOLLOWED)
    @JvmField
    var hasFollowedStore: Boolean = false
    override fun initViewBinding(): ActivityMeManageBinding =
        ActivityMeManageBinding.inflate(layoutInflater)

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.subscribeList.value!!).apply {
            addVhDelegate {
                SubStoresHolder(
                    it,
//                    viewModel.subscribeList.value!!,
                    pageTrackTag = this.hashCode().toString(),
                    { position, merchantWebVOF ->
                        CommonRoute.startStoreDetail(mActivity, merchantWebVOF.id)
                    }, {
                        if (viewModel.subHasNext.value == true && !viewModel.isAutoLoadMore) {
                            viewModel.isAutoLoadMore = true
                            viewModel.fetchMySubscribeMerchantWeb()
                        }
                    }
                )
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewBinding.rvSub.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        viewBinding.refresher.setEnableLoadMore(false)
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.loadRecommendStores(sceneCode = 5)
        }

        RecommendStorePart.handleVM(
            this,
            this,
            viewBinding.rv,
            viewBinding.refresher,
            viewModel,
            isNestedScrollingEnabled = false,
            SpmPageDef.MeStoresSubRecommendPage, this.hashCode().toString()
        )

        viewModel.fetchMySubscribeMerchantWeb(showLoading = true)
        viewModel.loadRecommendStores(sceneCode = 5)

        setListener()

        observeData()

        //同步订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) {
            if (it.id != null) {
                if (it.followed) {
                    if (it.merchant != null) {
                        viewModel.addSubscribeStore(it.merchant!!)
                    } else {
                        viewModel.fetchMySubscribeMerchantWeb(
                            showLoading = false,
                            initRefresh = true
                        )
                    }
                } else {
                    for ((index, post) in viewModel.subscribeList.value!!.withIndex()) {
                        if (post != null && post is MerchantWebVOF && it.id == post.id) {
                            viewModel.subscribeList.value!!.removeAt(index)
                            viewModel.subscribeList.value = viewModel.subscribeList.value
                            break
                        }
                    }
                }
            }
        }

        //同步取消店铺
        FlowBus.with<RemoveStoresEvent>(FlowConst.REMOVE_STORE_EVENT).register(this) {
            if (it.ids != null) {
                var removed = false
                for (id in it.ids!!) {
                    val first = viewModel.subscribeList.value!!.indexOfFirst { it.id == id }
                    viewModel.subscribeList.value!!.removeAt(first)
                    removed = true

                    refreshRecommendListSub(id, false)
                }
                if (removed) {
                    viewModel.subscribeList.value = viewModel.subscribeList.value
                }
            }
        }

        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.fetchMySubscribeMerchantWeb(showLoading = false, initRefresh = true)
        }
    }

    private fun refreshRecommendListSub(id: String, sub: Boolean) {
        //刷新推荐列表订阅状态
        val index = viewModel.recommendList.value!!.indexOfFirst { it.id == id }
        if (index >= 0) {
            val merchant = viewModel.recommendList.value!![index]
            if (merchant.subOrNot != sub) {
                ApolloValSetExt.setApolloVal<MerchantWebVOF>(merchant, "subOrNot", sub)
                viewModel.recommendList.value!![index] = merchant
            }
            viewModel.recommendList.value = viewModel.recommendList.value
        }
    }

    private fun setListener() {
        viewBinding.title.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }

            override fun onRightClick(titleBar: TitleBar?) {
                turnManage()
            }
        })

        viewBinding.llSearch.setOnClickListener {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                withInt(RoutePage.Search.ARG_SCENE, RoutePage.Search.SCENE.STORES.value)
            }
        }
        viewBinding.searchItemEmpty.setOnClickListener {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                withInt(RoutePage.Search.ARG_SCENE, RoutePage.Search.SCENE.STORES.value)
            }
        }
    }

    private fun turnManage() {
        navigationTo(RoutePage.Store.PAGE_MANAGE) {}
    }

    private fun observeData() {

        viewModel.subscribeList.observe(this) {
            if (viewBinding.rvSub.adapter == null) {
                viewBinding.rvSub.adapter = adapter//单位px
            } else {
                if (viewModel.subscribeList.value!!.isNotEmpty()) {
                    viewBinding.llSub.visibleOrGone(true) {}
                    adapter.notifyDataSetChanged()
                }
                if (viewModel.subscribePageNo <= 2) {
                    refreshStateView()
                }
            }
        }
        viewModel.recommendList.observe(this) {
            if (viewModel.recommendList.value!!.isNotEmpty()) {
                viewBinding.llRecommend.visibleOrGone(true) {}
                viewBinding.tvPopular.visibleOrGone(true) {}
                if (viewBinding.refresher.isLoading) {
                    viewBinding.refresher.finishLoadMore()
                }
                viewBinding.refresher.setEnableLoadMore(true)
            }
        }
    }

    //是否有订阅时处理布局
    private fun refreshStateView() {
        if (viewModel.subscribeList.value!!.isEmpty()) {//无订阅店铺
            viewBinding.viewP.setBackgroundColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_black12))

            viewBinding.title.title =
                CommUtils.getString(com.starblink.basic.style.R.string.Manage_Store)
            viewBinding.searchItemEmpty.visibleOrGone(true) {}
            viewBinding.searchItem.visibleOrGone(false) {}
            viewBinding.llSub.visibleOrGone(false) {}
        } else {
            viewBinding.viewP.setBackgroundColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray50))

            viewBinding.title.title =
                CommUtils.getString(com.starblink.basic.style.R.string.manage_store)
            viewBinding.searchItemEmpty.visibleOrGone(false) {}
        }
    }

    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.MySubStoresPage)
    }

    override fun onPause() {
        pageDisappear(SpmPageDef.MySubStoresPage)
        super.onPause()
    }
}